package com.ykt.interceptor;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.ykt.common.pay.wx.WxAppPayUtil;
import com.ykt.content.Content;
import com.ykt.model.Admin;
import com.ykt.model.Menu;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * 权限拦截
 *
 * @author TianJun
 */
public class AuthorityIntercept implements Interceptor {
    private static final Logger LOGGER = LoggerFactory.getLogger(AuthorityIntercept.class);

    private List<Menu> menuList;//用户的操作权限


    @Override
    public void intercept(Invocation ai) {
        Controller ctrl = ai.getController();

        // 微信支付则不拦截
        if (WxAppPayUtil.isPayServerCallBack(ctrl.getRequest())) {
            ai.invoke();
            return;
        }

        Admin admin = ctrl.getSessionAttr(Content.SESSION_LOGIN_USER);
        menuList = admin.getMenuCommon();

        String actionKey = ai.getActionKey();// 访问请求路径  例: /product/add
        String method = ai.getMethodName();// 访问的方法名   例: add
        String controllerKey = ai.getControllerKey();// 访问的控制器 例:/product

        // 如果系统管理员 直接跳过权限验证
        if (admin.getInt("id") == 1) {
            ctrl.setAttr("hasAdd", true);
            ctrl.setAttr("hasEdit", true);
            ctrl.setAttr("hasDel", true);
            ctrl.setAttr("hasView", true);
            ai.invoke();
            return;
        }

        // 不需要判断权限的方法名（一般是些ajax组件 不是页面）
        String filter = "combobox, grid, combotree, treeDataGrid, swfup, upload,batchOperator, "
        		+ "marketShop,cameraShop,community,findCommunity,comboboxMarketCategory,comboboxShopCategory,"
        		+ "findCamera,camera,savaCamera,deleteCamera,savaCommunity,deleteCommunity"
        		+ "exportFurchaseReport,exportSortingReport,excelExport";
        if (method != null && filter.contains(method)) {
            LOGGER.info(actionKey + " 有权限");
            ai.invoke();
            return;
        }

        // 如果方法是save 并且有and或者edit权限
        if ("save".equals(method)) {
            if (hasPerm(controllerKey + "/add") || hasPerm(controllerKey + "/edit")) {
                ai.invoke();
                return;
            }
        }

        // 判断是否有请求权限
        if (hasPerm(actionKey)) {
            if ("index".equals(method)) {
                //如果是index 添加页面按钮判断
                ctrl.setAttr("hasAdd", hasPerm(controllerKey + "/add"));
                ctrl.setAttr("hasEdit", hasPerm(controllerKey + "/edit"));
                ctrl.setAttr("hasDel", hasPerm(controllerKey + "/del"));
                ctrl.setAttr("hasView", hasPerm(controllerKey + "/view"));
            }
            LOGGER.info(actionKey + " 有权限");
            ai.invoke();
            return;
        }

        LOGGER.info(actionKey + " 没权限");
        ctrl.render("/common/authority_error.html");
    }

    //是否有权限 返回true代表有权限
    public boolean hasPerm(String key) {
        if (key != null) {
            for (Menu m : menuList) {
                if (key.equals(m.get("url")))
                    return true;
            }
        }
        return false;
    }
}
